package com.example.blades.myhandler;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class HandlerActivity extends AppCompatActivity {

    private Button btnStart=null;
    private Button btnEnd=null;
    private Button btnJump=null;

    /*1.创建一个Handler对象，*/
    Handler handler=new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);

        btnStart=(Button)findViewById(R.id.btn_start);
        btnEnd=(Button)findViewById(R.id.btn_end);
        btnStart.setOnClickListener(new StartButtonListener());
        btnEnd.setOnClickListener(new EndButtonListener());

        btnJump=(Button)findViewById(R.id.btn_jump);
        btnJump.setOnClickListener(new BtnJumpClickListener());
    }

    class StartButtonListener implements View.OnClickListener
    {
        @Override
        public void onClick(View v) {
            /*2.调用Handler的post方法，将要执行的线程对象添加到队列当中，同样下面也有停止按钮*/
            handler.post(updateThread);
        }
    }


    class EndButtonListener implements View.OnClickListener
    {
        @Override
        public void onClick(View v) {
            handler.removeCallbacks(updateThread);
        }
    }

    /*3.将要执行的操作写在线程对象的run方法当中*/
    Runnable updateThread=new Runnable() {
        @Override
        public void run() {
            System.out.print("UpdateThread");
            Log.v("Tag","UpdateThread");
            /*在run方法内部，执行postDelayed或者是post方法*/
            handler.postDelayed(updateThread,2000);
        }
    };


    /*用于实现页面跳转的ClickListener*/
    class BtnJumpClickListener implements View.OnClickListener
    {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent();
            intent.setClass(HandlerActivity.this,BarStart.class);
            startActivity(intent);
        }
    }
}



